//
//  MyCacheManager.swift
//  RIBsTest
//
//  Created by lvzhao on 2024/5/25.
//

import Foundation

// MARK - 对外暴漏接口, 用户只可以使用这两个接口, 进行数据的存储, 获取
public protocol ICacheManager {
    //userDefault plist file 使用这个2个接口
    func pull<T>(key: String, type: MyStoreType, isDecrypt: Bool) -> T?
    func push<T>(key: String, type: MyStoreType, data: T, isEndrypt: Bool) -> MyStoreErrorCode
}


open class MyCacheManager: ICacheManager {
    
    public let fileCache = MyFileCacheBehavior()
    public let plistCache = MyPlistCacheBehavior()
    public let defaultCache = MyDefaultCacheBehavior()
    
    private static var _sharedInstance: MyCacheManager?
    
    public class func getShared() -> MyCacheManager {
        guard let instance = _sharedInstance else {
            _sharedInstance = MyCacheManager()
            return _sharedInstance!
        }
        return instance
    }
    
    private init() {
        
    } // 私有化init方法
    
    //销毁单例对象
    public class func destroy() {
        _sharedInstance = nil
    }

    public func eraseFile(for key: String) {
        fileCache.eraseFile(for: key)
    }
    
    
    /// 唯一数据存储方法，支持数据加密处理
    ///
    /// - Parameters:
    ///   - key: 存储的路径
    ///   - type: 数据存储方式
    ///   - isEncrypt: 是否需要加密
    /// - Returns: 返回是否存储成功
    @discardableResult
    public func push<T>(key: String, type: MyStoreType, data: T, isEndrypt isEncrypt: Bool) -> MyStoreErrorCode {
        switch type {
        case .plist:
            return plistCache.set(key: key, data: data, isEncrypt: isEncrypt)
        case .file:
            return fileCache.set(key: key, data: data, isEncrypt: isEncrypt)
        case .userDefault:
            return defaultCache.set(key: key, data: data, isEncrypt: isEncrypt)
        }
    }

    /// 唯一数据获取方法，支持数据解密处理
    ///
    /// - Parameters:
    ///   - key: 存储的路径
    ///   - type: 数据存储方式
    ///   - isDecrypt: 是否需要解密
    /// - Returns: 返回用户存储的数据
    @discardableResult
    public func pull<T>(key: String, type: MyStoreType, isDecrypt: Bool) -> T? {
        switch type {
        case .plist:
            return plistCache.get(key: key, isDecrypt: isDecrypt)
        case .file:
            return fileCache.get(key: key, isDecrypt: isDecrypt)
        case .userDefault:
            return defaultCache.get(key: key, isDecrypt: isDecrypt)
        }
    }
    
   

}



